<template>
    <div>
        <slot name="left"></slot>
        <span ref="number" :class="clountClass" :id="eleId"></span>
        <slot name="right"></slot>
    </div>
</template>

<script>
  import CountUp from 'countup'

  export default {
    name: "CountTo",
    computed: {
      eleId() {
        return 'count_up_${this._uid}'
      },
      clountClass() {
        return [
          'count-to-number',
          this.className
        ]
      }
    },
    data() {
      return ({
        counter: {}
      });
    }
    , props: {
      /**
       * @description 起始值
       */
      startVal: {
        type: Number,
        default: 0
      },
      /**
       * @description 最终值
       */
      endVal: {
        type: Number,
        required: true
      },
      /**
       * @description 小数点后保留几位小数
       */
      decimals: {
        type: Number,
        default: 0
      },
      /**
       * @description 动画延迟 默认毫秒
       */
      delay: {
        type: Number,
        default: 0
      },
      /**
       * @description 渐变时长
       */
      duration: {
        type: Number,
        default: 1
      },
      /**
       * @description 是否使用变速效果
       */
      userEasing: {
        type: Boolean,
        default: false
      },
      /**
       * @description 是否使用变速效果
       */
      userGrouping: {
        type: Boolean,
        default: true
      },
      /**
       * @description 分组符号
       */
      spearator: {
        type: String,
        default: ','
      },
      /**
       * @description 整数和小数分割符号
       */
      decimal: {
        type: String,
        default: '.'
      },
      className: {
        type: String,
        default: ''
      }
    },
    methods: {
      getCount() {
        return this.$refs.number.innerText
      }
    },
    watch: {
      endVal(newVal, oldVal) {
        this.counter.update(newVal)
        setTimeout(() => {
          this.$nextTick(() => {
            this.$emit('on-animation-end', Number(this.getCount()))
          })
        }, this.duration * 1000 + 5)
      }
    },
    mounted() {
      this.$nextTick(() => {
        //
        this.counter = new CountUp(this.eleId, this.startVal, this.endVal, this.decimals, this.duration, {
          userEasing: this.userEasing,
          userGrouping: this.userGrouping,
          separator: this.spearator,
          decimal: this.decimal
        }),
          setTimeout(() => {
            this.counter.start()
          }, this.delay)
      })
    }
  }
</script>

<style scoped>

</style>
